package com.docmanage.web.controller.common;

import com.docmanage.am.domain.vo.FileVO;
import com.docmanage.common.config.MinioConfig;
import com.docmanage.common.core.domain.AjaxResult;
import com.docmanage.common.utils.file.MinioUtil;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件上传通用请求处理
 *
 * @author docmanage
 */
@RestController
@RequestMapping("/minio")
public class MinioController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Value("${minio.bucket}")
    private String bucket;

    /**
     * 通用文件下载
     *
     * @param fileName
     * @param response
     */
        @GetMapping("/download")
    public void fileDownload(@RequestParam String fileName, HttpServletResponse response) {
        MinioUtil.downloadFile(bucket, fileName, response);
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestBody MultipartFile file) throws Exception {
        try {
            String filename = file.getOriginalFilename();
            String url = MinioUtil.uploadFile(bucket, filename, file);
            //补充文件上传后返回前端的文件对象抽象出set对象
            FileVO fileVO = new FileVO();
            fileVO.setFileName(filename);
            fileVO.setUrl(MinioConfig.getCdn()+url);
            return AjaxResult.success("文件上传成功！", fileVO);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(@RequestBody List<MultipartFile> files) throws Exception {
        try {
            if (CollectionUtils.isEmpty(files)) {
                throw new RuntimeException("至少上传一个文件");
            }
            List<FileVO> list = new ArrayList<>();
            files.forEach(file -> {
                try {
                    String filename = file.getOriginalFilename();
                    String url = MinioUtil.uploadFile(bucket, filename, file);
                    FileVO fileVO = new FileVO();
                    fileVO.setFileName(filename);
                    fileVO.setUrl(MinioConfig.getCdn()+url);
                    list.add(fileVO);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            return AjaxResult.success("文件上传成功！", list);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除文件  表单提交数据时删除
     * @param fileName
     * @return
     */
    @DeleteMapping
    @ApiOperation(value = "删除文件  表单提交数据时删除")
    public AjaxResult delFile(String fileName){
        try {
            Boolean isDel = MinioUtil.delFile(bucket, fileName);
            if (isDel) {
                return AjaxResult.success("文件删除成功！", isDel);
            }
            return AjaxResult.error("文件删除失败！", isDel);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
